package com.one.login.common;

import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtostuffIOUtil;
import com.dyuproject.protostuff.runtime.RuntimeSchema;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

public abstract class RedisBase {

	protected JedisPool jedisPool;

	public RedisBase(JedisPool jedisPool) {
		this.jedisPool = jedisPool;
	}

	/**
	 * 
	 * @param c
	 *            反序列化类型
	 * @param zone
	 *            域
	 * @param id
	 *            id
	 * @return
	 */
	public <T> T getObject(Class<T> c, String zone, String id) {
		try {
			RuntimeSchema<T> schema = RuntimeSchema.createFrom(c);
			Jedis jedis = jedisPool.getResource();
			try {
				String key = zone + ":" + id;
				byte[] bytes = jedis.get(key.getBytes());
				if (bytes != null) {
					T obj = schema.newMessage();
					ProtostuffIOUtil.mergeFrom(bytes, obj, schema);
					return obj;
				}
			} finally {
				jedis.close();
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return null;
	}

	/**
	 * 
	 * @param c
	 *            序列化类型
	 * @param obj
	 *            被序列化的对象
	 * @param zone
	 *            域
	 * @param id
	 *            标识
	 * @return
	 */
	public <T> String setObject(Class<T> c, T obj, String zone, String id) {
		try {
			RuntimeSchema<T> schema = RuntimeSchema.createFrom(c);
			Jedis jedis = jedisPool.getResource();
			try {
				String key = zone + ":" + id;
				byte[] bytes = ProtostuffIOUtil.toByteArray(obj, schema,
						LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE));
				return jedis.set(key.getBytes(), bytes);
			} finally {
				jedis.close();
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return null;
	}

	/**
	 * 获取过期时间
	 * 
	 * @param zone
	 *            域
	 * @param id
	 *            id
	 * @return
	 */
	public Long getTTL(String zone, String id) {
		try {
			Jedis jedis = jedisPool.getResource();
			try {
				String key = zone + ":" + id;
				return jedis.ttl(key.getBytes());
			} finally {
				jedis.close();
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return null;
	}

	/**
	 * 设置过期时间
	 * 
	 * @param zone
	 *            域
	 * @param id
	 *            id
	 * @return
	 */
	public Long setTTL(String zone, String id, Integer seconds) {
		try {
			Jedis jedis = jedisPool.getResource();
			try {
				String key = zone + ":" + id;
				return jedis.expire(key.getBytes(), seconds);
			} finally {
				jedis.close();
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return null;
	}

}
